package com.aliyun.oss.websocket;

import com.aliyun.oss.config.GetHttpSessionConfig;
import com.aliyun.oss.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpSession;
import jakarta.websocket.CloseReason;
import jakarta.websocket.EndpointConfig;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@ServerEndpoint(value = "/websocket/{token}", configurator = GetHttpSessionConfig.class)
public class WebSocketServer {
    //    定义一个map，存放所有在线的连接
    private static final java.util.Map<String, Session> webSocketMap = new java.util.HashMap<>();
    private HttpSession httpSession;
    private Session session;
    private Integer userId;

    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token) {
        this.session = session; // 赋值当前Session
        Claims claims = JwtUtils.analysisToken(token);
        String id = (String) claims.get("id");
        System.out.println("用户id：" + id);
        webSocketMap.put(id, session);
    }

    //    定义一个方法，向所有的浏览器发送消息
    public static void sendMessage(String message) {
        for (String key : webSocketMap.keySet()) {
            Session session = webSocketMap.get(key);
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
}


